<template>
  <div class="shift-type-management">
    <el-card shadow="hover">
      <div class="card-header">
        <h2>排班类型管理</h2>
        <el-button type="primary" @click="showAddDialog">添加排班类型</el-button>
      </div>

      <el-table :data="shiftTypes" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column prop="work_time" label="工作时间" width="180"></el-table-column>
        <el-table-column prop="cycle" label="循环配置" width="180">
          <template #default="{ row }">{{ formatCycle(row.cycle) }}</template>
        </el-table-column>
        <el-table-column prop="holiday_work_schedule" label="节假日是否排班" width="120">
          <template #default="{ row }"><el-switch v-model="row.holiday_work_schedule" @change="handleSwitchChange(row, 'holiday_work_schedule', row.holiday_work_schedule)" /></template>
        </el-table-column>
        <el-table-column prop="adjust_work_day_schedule" label="调休日是否排班" width="120">
          <template #default="{ row }"><el-switch v-model="row.adjust_work_day_schedule" @change="handleSwitchChange(row, 'adjust_work_day_schedule', row.adjust_work_day_schedule)" /></template>
        </el-table-column>
        <el-table-column prop="applicable_type" label="适用人员" width="120">
          <template #default="{ row }">{{ formatApplicableType(row.applicable_type) }}</template>
        </el-table-column>
        <el-table-column prop="is_enabled" label="启用状态" width="120">
          <template #default="{ row }"><el-switch v-model="row.is_enabled" @change="handleSwitchChange(row, 'is_enabled', row.is_enabled)" /></template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteShiftType(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑排班类型对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入排班类型名称"></el-input>
        </el-form-item>
        <el-form-item label="循环配置" prop="cycle">
          <div class="cycle-checkbox-group">
            <el-checkbox-group v-model="cycleDays">
              <el-checkbox value="1" border>周一</el-checkbox>
              <el-checkbox value="2" border>周二</el-checkbox>
              <el-checkbox value="4" border>周三</el-checkbox>
              <el-checkbox value="8" border>周四</el-checkbox>
              <el-checkbox value="16" border>周五</el-checkbox>
              <el-checkbox value="32" border>周六</el-checkbox>
              <el-checkbox value="64" border>周日</el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>
        <el-form-item label="节假日是否排班">
          <el-switch v-model="form.holiday_work_schedule"></el-switch>
        </el-form-item>
        <el-form-item label="调休日是否排班">
          <el-switch v-model="form.adjust_work_day_schedule"></el-switch>
        </el-form-item>
        <el-form-item label="适用人员" prop="applicable_type">
          <el-select v-model="form.applicable_type" placeholder="请选择适用人员类型">
            <el-option label="内勤" :value="1"></el-option>
            <el-option label="外勤" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-switch v-model="form.is_enabled"></el-switch>
        </el-form-item>
        <el-form-item label="工作时间">
          <el-input v-model="form.work_time" placeholder="请输入工作时间，如: 09:00-18:00"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import api from '../services/api';

// 状态变量
const shiftTypes = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref('添加排班类型');
const formRef = ref(null);
const form = ref({
  name: '',
  cycle: 0,
  holiday_work_schedule: false,
  adjust_work_day_schedule: false,
  applicable_type: 1,
  is_enabled: true,
  work_time: ''
});
const cycleDays = ref([]);
const rules = ref({
  name: [{ required: true, message: '请输入排班类型名称', trigger: 'blur' }],
  applicable_type: [{ required: true, message: '请选择适用人员类型', trigger: 'blur' }]
});
const currentId = ref(null);

// 格式化适用人员显示
const formatApplicableType = (typeValue) => {
    const types = {
      1: '内勤',
      2: '外勤'
    };
    return types[typeValue] || '未知';
  };

// 格式化循环配置显示
const formatCycle = (cycleValue) => {
  if (!cycleValue) return '未设置';
  const days = [
    { value: 1, name: '周一' },
    { value: 2, name: '周二' },
    { value: 4, name: '周三' },
    { value: 8, name: '周四' },
    { value: 16, name: '周五' },
    { value: 32, name: '周六' },
    { value: 64, name: '周日' }
  ];
  return days.filter(day => (cycleValue & day.value)).map(day => day.name).join(', ');
};

// 监听cycleDays变化，更新form.cycle
const updateCycleValue = () => {
  form.value.cycle = cycleDays.value.reduce((sum, day) => sum + Number(day), 0);
};
cycleDays.value = [];
cycleDays.value.forEach(updateCycleValue);
cycleDays.value = cycleDays.value;

// 处理开关变化
const handleSwitchChange = async (row, field, value) => {
  // 保存原始值
  const originalValue = row[field];
  try {
    // 创建一个只包含变化字段的对象
    const updatedData = { [field]: value };
    await api.shiftTypes.update(row.id, updatedData);
    //ElMessage.success('更新成功');
    // 更新成功后，同步更新shiftTypes数组中的对应项
    const index = shiftTypes.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      shiftTypes.value[index][field] = value;
    }
  } catch (error) {
    // 更新失败，回滚开关状态
    row[field] = originalValue;
    ElMessage.error('更新失败: ' + (error.response?.data?.error || error.message));
  }
};

// API请求
const fetchShiftTypes = async () => {
  try {
    const response = await api.shiftTypes.getAll();
    // 确保布尔类型字段正确转换
    shiftTypes.value = response.map(item => ({
      ...item,
      holiday_work_schedule: Boolean(item.holiday_work_schedule),
      adjust_work_day_schedule: Boolean(item.adjust_work_day_schedule),
      is_enabled: Boolean(item.is_enabled),
      work_time: item.work_time || ''
    }));
  } catch (error) {
    ElMessage.error('获取排班类型失败: ' + (error.response?.data?.error || error.message));
  }
};

const addShiftType = async () => {
  try {
    await api.shiftTypes.create(form.value);
    ElMessage.success('排班类型添加成功');
    dialogVisible.value = false;
    fetchShiftTypes();
  } catch (error) {
    ElMessage.error('添加排班类型失败: ' + (error.response?.data?.error || error.message));
  }
};

const updateShiftType = async () => {
  try {
    await api.shiftTypes.update(currentId.value, form.value);
    ElMessage.success('排班类型更新成功');
    dialogVisible.value = false;
    fetchShiftTypes();
  } catch (error) {
    ElMessage.error('更新排班类型失败: ' + (error.response?.data?.error || error.message));
  }
};

const deleteShiftType = async (id) => {
  await ElMessageBox.confirm('确定要删除这个排班类型吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });
  await api.shiftTypes.delete(id);
  ElMessage.success('排班类型删除成功');
  fetchShiftTypes();
};

// 表单提交
const submitForm = async () => {
  await formRef.value.validate();
  updateCycleValue();
  if (currentId.value) {
    await updateShiftType();
  } else {
    await addShiftType();
  }
};

// 显示添加对话框
const showAddDialog = () => {
  currentId.value = null;
  dialogTitle.value = '添加排班类型';
  form.value = {
          name: '',
          cycle: 0,
          exclude_holidays: false,
          applicable_type: 1,
          is_enabled: true,
          work_time: ''
        };
  cycleDays.value = [];
  dialogVisible.value = true;
};

// 显示编辑对话框
const showEditDialog = (row) => {
  currentId.value = row.id;
  dialogTitle.value = '编辑排班类型';
  form.value = {
    name: row.name,
    cycle: row.cycle,
    exclude_holidays: row.exclude_holidays,
    applicable_type: row.applicable_type,
    is_enabled: row.is_enabled,
    work_time: row.work_time || ''
  };
  // 将cycle值转换为选中的天数
  cycleDays.value = [];
  const days = [1, 2, 4, 8, 16, 32, 64];
  days.forEach(day => {
    if (row.cycle & day) {
      cycleDays.value.push(day.toString());
    }
  });
  dialogVisible.value = true;
};

// 页面加载时获取数据
onMounted(() => {
  fetchShiftTypes();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.cycle-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
</style>